/**
 * @Title: DailyReportSyncLogic.java
 * @Package: com.jason.fingerprint.logic
 * @Descripton: TODO
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月17日 上午10:58:52
 * @Version: V1.0
 */
package com.jason.fingerprint.logic;

import android.os.Handler;
import android.os.Message;
import android.util.Log;
import com.google.gson.GsonBuilder;
import com.jason.fingerprint.AppContext;
import com.jason.fingerprint.AppGlobal;
import com.jason.fingerprint.beans.BaseBean;
import com.jason.fingerprint.beans.DailyReportBean;
import com.jason.fingerprint.beans.ui.ImageOrAudioBean;
import com.jason.fingerprint.common.DateFormat;
import com.jason.fingerprint.common.UIHelper;
import com.jason.fingerprint.configs.HttpConfig;
import com.jason.fingerprint.utils.CharUtils;
import com.jason.fingerprint.utils.CodecUtils;
import com.jason.fingerprint.utils.DataUtils;
import com.jason.fingerprint.utils.ToastUtil;

import org.kymjs.aframe.core.KJException;
import org.kymjs.aframe.utils.StringUtils;
import org.kymjs.aframe.utils.SystemTool;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: DailyReportSyncLogic
 * @Description: 上传日常报到信息到服务器
 * @Author: Jason.Zhang zhangyujn1989ok@gmail.com
 * @Date: 2014年11月17日 上午10:58:52
 */
public class DailyReportSyncLogic extends Logic {

    private static final String TAG = "DailyReportSyncLogic";

    private Handler mHandler;
    private boolean mIsCallBack = false;// 是否有回调，此需要Handle,默认不回调
    private Message mMessage;
    private int mSize = -1;// 总共要上传的条数
    private int mIndex = 0;// 上传到第几条

    private List<DailyReportBean> mDailyReportBeans = new ArrayList<DailyReportBean>();

    public DailyReportSyncLogic() {

    }

    public DailyReportSyncLogic(AppContext appContext, Handler handler) {
        super(appContext);
        this.mHandler = handler;
        this.mMessage = new Message();
    }

    public DailyReportSyncLogic(AppContext appContext, Handler handler,
                                boolean isCallBack) {
        super(appContext);
        this.mHandler = handler;
        this.mMessage = new Message();
        this.mIsCallBack = isCallBack;
    }

    /*
     * (non-Javadoc)
     *
     * @see com.jason.fingerprint.logic.Logic#execute()
     */
    @Override
    public void execute() {
        try {
            mDailyReportBeans = mKjdb.findAllByWhere(DailyReportBean.class,
                    " state = 1 ", "updateTime");
        } catch (Exception e) {
            Log.i(TAG, "execute select the log is error ,the exception message is :" + e.getMessage());
        }
        if (mDailyReportBeans != null && !mDailyReportBeans.isEmpty()) {
            mSize = mDailyReportBeans.size();
            upload();
        } else {
            mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
            send();
        }
    }

    /*
     * (non-Javadoc)
     *
     * @see com.jason.fingerprint.logic.Logic#send()
     */
    @Override
    public void send() {
        // TODO Auto-generated method stub
        if (mIsCallBack) {
            mHandler.sendMessage(mMessage);
            mMessage = new Message();
        }
    }


    private void upload(){
        Map<String ,String> params = new HashMap<String, String>();
        Map<String ,File> fileParams = new HashMap<String, File>();
        if (mIndex >= mSize) {
            mMessage.what = UIHelper.FILE_UPLOAD_SUCCESS;
            send();
            return;
        }
        final DailyReportBean dailyReportBean = mDailyReportBeans.get(mIndex);
        if (dailyReportBean == null) {
            mIndex++;
            upload();
            return;
        }
        put(AppGlobal.HTTP_PARAM_IMEI, mImei, params);
        ImageOrAudioBean audioBean = mKjdb.findOneByWhere(ImageOrAudioBean.class, "serviceId = 1 and parentId= '" + dailyReportBean.getId() + "'");
        if (audioBean != null){
            Log.i(TAG,"uploadDailyReportInfo audioBean:" + audioBean.toString());
            if (!StringUtils.isEmpty(audioBean.getFilePath())){
                File file = new File(audioBean.getFilePath());
                if (file.exists() && file.isFile()){
                    String fileName = audioBean.getFileName();
                    if (audioBean.getFileType() == 1) {
                        fileName = fileName;
                    } else {
                        fileName += ".amr";
                    }
                    put("fileInputFileName", fileName,params);
                    put("type", String.valueOf(audioBean.getFileType() == 1 ? 0 : 1),params);
                    Log.i(TAG, "----->path:" + audioBean.getFilePath());
                    fileParams.put("fileInput", new File(audioBean.getFilePath()));
                }
            }
        }
        put("serviceId", String.valueOf(UploadToTempSyncLogic.SERVICE.SERVICE_DAILY_REPORT), params);
        put("rymcId", dailyReportBean.getRymcId(),params);
        put("startTime", DataUtils.converDatLongToString(dailyReportBean.getStartTime(), DateFormat.DATE_YMD_HMS),params);
        put("registrationType",String.valueOf(dailyReportBean.getRegistrationType()),params);
//		put("endTime", DataUtils.converDatLongToString(dailyReportBean.getUpdateTime(), DateFormat.DATE_YMD_HMS));
        String url = HttpConfig.POST_URL_FILEUPLOAD_UPLOADTOTEMP;
        new PostFile(url,params,fileParams,new PostFile.CallBack(){

            @Override
            public void onSuccess(Object object) {
                Log.i(TAG, "----->arg0:" + object.toString());
                String result = null;
                BaseBean bean = null;
                try {
                    result = CodecUtils.base64Decode(object.toString());
                    Log.i(TAG, "----->Result:" + result);
                    bean = new GsonBuilder().create().fromJson(result,
                            BaseBean.class);
                } catch (Exception e) {
                    mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
                    send();
                    return;
                }
                if (bean != null && bean.isSuccess()) {
                    dailyReportBean.setState(2);
                    mKjdb.update(dailyReportBean);
                    mIndex++;
                    upload();
                } else {
                    mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
                    send();
                }
            }

            @Override
            public void onFailure(int arg1, String arg2) {
                if (arg1 == UIHelper.HTTP_CODE_TIMEOUT){
                    mMessage.what = UIHelper.HTTP_CODE_TIMEOUT;
                }else {
                    mMessage.what = UIHelper.FILE_UPLOAD_FAIL;
                }
                send();
            }
        }).start();

    }

    public Map<String ,String> put(String key, String value,Map<String ,String> params) {
        if (params == null){
            params = new HashMap<String, String>();
        }
        if (key != null) {
            if (!StringUtils.isEmpty(value)) {

                if (CharUtils.isChinese(value)) {
                    params.put(key, CodecUtils.base64Encode(value));
                }else {
                    params.put(key, value);
                }

            }
        } else {
            throw new KJException("key is NULL");
        }
        return params;
    }

    /* (non-Javadoc)
     * @see com.jason.fingerprint.logic.Logic#destory()
     */
    @Override
    public void destory() {
        // TODO Auto-generated method stub

    }

}
